﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;

namespace CourseManage.Data
{
    public class CourseManageContext:DbContext
    {
        public CourseManageContext(DbContextOptions<CourseManageContext> options)
            : base(options)
        {
        }

        public DbSet<User> Users { get; set; }

        public DbSet<Teacher> Teachers { get; set; }
        public DbSet<Student> Students { get; set; }
        public DbSet<Course> Courses { get; set; }
        public DbSet<RealCourse> RealCourses { get; set; }
        public DbSet<CourseSelection> Grades { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<User>()
               .HasDiscriminator<UserType>(o => o.UserType)
               .HasValue<User>(0)
               .HasValue<Student>(UserType.学生)
               .HasValue<Teacher>(UserType.教师);

            modelBuilder.Entity<RealCourse>()
               .HasKey(o => new
               {
                   o.CourseId,
                   o.TeacherId
               });

            modelBuilder.Entity<RealCourse>()
                .HasOne(o => o.Teacher)
                .WithMany(o => o.RealCourses)
                .HasForeignKey(o => o.TeacherId);
            modelBuilder.Entity<RealCourse>()
                .HasOne(o => o.Course)
                .WithMany(o => o.RealCourses)
                .HasForeignKey(o => o.CourseId);

            modelBuilder.Entity<CourseSelection>()
                .HasOne(o => o.Teacher)
                .WithMany()
                .HasForeignKey(o => o.TeacherId)
                .OnDelete(DeleteBehavior.Restrict);

            modelBuilder.Entity<CourseSelection>()
                .HasOne(o => o.Course)
                .WithMany()
                .HasForeignKey(o => o.CourseId)
                .OnDelete(DeleteBehavior.Restrict);

            modelBuilder.Entity<CourseSelection>()
                .HasOne(o => o.Student)
                .WithMany(o=>o.CourseSelections)
                .HasForeignKey(o => o.StudentId)
                .OnDelete(DeleteBehavior.Restrict);

            modelBuilder.Entity<CourseSelection>()
                .Property(o => o.Score)
                .HasColumnType("decimal(18,2)");




        }
    }
}
